<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区 -->
    <el-card class="box-card">
      <el-alert title="添加商品详细信息" type="info" center show-icon></el-alert>

      <!-- 步骤条 -->
      <el-steps :active="+activeName" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tabs标签页 -->
      <!-- 使用form标签包裹的原因：为了后期表单校验等操作 -->
      <el-form label-width="100px" :model="addForm" ref="addFormRef" :rules="addFormRules">
        <el-tabs
          tab-position="left"
          v-model="activeName"
          :before-leave="tabsLeaveBefore"
          @tab-click="tabsClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="selectThreeCat">
              <el-cascader
                v-model="addForm.selectThreeCat"
                :options="catList"
                :props="{ expandTrigger: 'hover', value: 'cat_id', label: 'cat_name' }"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="item in manyParamsList"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <!-- v-model == 一个数组，包含被选中的内容 -->
              <el-checkbox-group v-model="item.attr_vals_array2">
                <el-checkbox
                  v-for="item2 in item.attr_vals_array"
                  :key="item2"
                  :label="item2"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyParamsList"
              :key="item.attr_id"
              :label="item.attr_name"
              label-width="150px"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:11333/api/private/v1/upload"
              :on-success="uploadSuccess"
              :on-remove="uploadRemove"
              list-type="picture"
              :headers="uploadHeaders"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quillEditor v-model="addForm.goods_introduce"></quillEditor>
            <el-button type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
export default {
  components: {
    quillEditor
  },
  created () {
    this.renderList()
  },
  data () {
    return {
      // 将步骤条与tabs绑定,这里需要用到字符串(不是数字)，否则会在触发tabs标签页离开之前事件（selectCatId一开始就是0），右侧表格不显示
      activeName: '0',

      // 基本信息表单
      addForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        // 接收选取的分类信息，数组
        selectThreeCat: [],
        // 存储上传图片的路径
        pics: [],
        // 文本，描述
        goods_introduce: '',
        // 收集分类级别id
        goods_cat: '',
        // 接收参数、属性
        attrs: []
      },
      // 基本信息表单简单校验
      addFormRules: {
        goods_name: [
          { required: true, message: '商品名称必填', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '商品价格必填', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '商品重量必填', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '商品数量必填', trigger: 'blur' }
        ],
        selectThreeCat: [
          { required: true, message: '商品分类必选', trigger: 'change' }
        ]
      },
      // 商品级联选择分类数据
      catList: [],

      // 接收第三级别分类id值
      selectCatId: 0,

      // 上传图片请求头信息设置
      uploadHeaders: {
        Authorization: sessionStorage.getItem('token')
      },

      // 商品参数列表
      manyParamsList: [],
      // 商品属性列表
      onlyParamsList: []

      // 收集所有数据
    }
  },

  methods: {
    // 获取所有的商品，以便级联选择器渲染数据
    async renderList () {
      const { data: dt } = await this.$http.get('categories', {
        params: { type: 3 }
      })
      // console.log(dt)
      this.catList = dt.data
    },

    // 级联选择后的回调函数
    handleChange () {
      // console.log(this.addForm.selectThreeCat)
      if (this.addForm.selectThreeCat.length === 3) {
        this.selectCatId = this.addForm.selectThreeCat[2]
        // 将各级别id值(selectId)由数组转换成字符串，且用 ， 分隔
        this.addForm.goods_cat = this.addForm.selectThreeCat.join(',')
      } else {
        this.selectCatId = 0
        this.addForm.selectThreeCat = []
      }
    },

    // 切换tabs标签页之前的回调函数
    tabsLeaveBefore () {
      if (this.selectCatId === 0) {
        this.$message.error('请先选取第3级别分类！')
        return false
      }
    },
    // 点击tabs标签页时触发的事件
    async tabsClick () {
      if (this.activeName === '1') {
        const { data: dt } = await this.$http.get(
          `categories/${this.selectCatId}/attributes`,
          { params: { sel: 'many' } }
        )
        // console.log(dt.data)

        // 将参数中的attr_vals由字符串转换成数组，通过空格分割
        dt.data.forEach(item => {
          item.attr_vals_array = item.attr_vals.split(' ')
          item.attr_vals_array2 = item.attr_vals.split(' ')
        })
        this.manyParamsList = dt.data
        // console.log(this.manyParamsList)
      } else if (this.activeName === '2') {
        const { data: dt2 } = await this.$http.get(
          `categories/${this.selectCatId}/attributes`,
          { params: { sel: 'only' } }
        )
        // console.log(dt2)
        this.onlyParamsList = dt2.data
        console.log(this.onlyParamsList)
      }
    },

    // 上传图片相关方法
    // 上传成功的钩子
    uploadSuccess (res) {
      // console.log(res.data.tmp_path)
      // this.addForm.pics.push(res.data.tmp_path)
      const k = { pic: res.data.tmp_path }
      this.addForm.pics.push(k)
      console.log(this.addForm.pics)
    },
    // 删除的钩子
    uploadRemove (res) {
      console.log(res)
      const picPath = res.response.data.tmp_path
      const index = this.addForm.pics.findIndex(item => {
        return item.pic === picPath
      })
      this.addForm.pics.splice(index, 1)
      console.log(this.addForm.pics)
    },

    // 收集数据发请求
    addGoods () {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          this.activeName = '5'
          this.manyParamsList.forEach(item => {
            const k = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals_array2.join(' ')
            }
            this.addForm.attrs.push(k)
          })
          this.onlyParamsList.forEach(item => {
            const k = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            }
            this.addForm.attrs.push(k)
          })

          const { data: dt } = await this.$http.post('goods', this.addForm)
          // console.log(dt)
          this.$message.success(dt.meta.msg)
          this.$router.push('/goods')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-alert {
  margin-bottom: 20px;
}
.el-steps {
  margin-bottom: 20px;
}
</style>
